<template>
  <PageCard title="IP 地址查询">
    <n-spin :show="loading">
      <div class="w-full max-w-[600px] mx-auto p-4 md:p-4">
        <n-space vertical size="large" class="w-full">
          <div class="flex gap-2 w-full md:flex-row flex-col">
            <n-input
              v-model:value="ipValue"
              placeholder="请输入 IP 地址"
              size="large"
              clearable
              @keydown.enter="handleSearch"
              class="flex-1"
            />
            <n-button 
              type="primary" 
              size="large" 
              @click="handleSearch"
              class="flex-shrink-0 md:w-auto w-full"
            >
              查询
            </n-button>
          </div>

          <n-alert v-if="error" title="查询出错" type="error" class="w-full">
            {{ error }}
          </n-alert>

          <div v-if="result" class="mt-6 p-6 bg-white/90 rounded-lg shadow-md text-center md:mt-8 md:p-8">
            <span class="block text-sm text-gray-600 mb-2">查询结果:</span>
            <n-gradient-text type="success" class="text-lg md:text-xl">
              {{ result }}
            </n-gradient-text>
          </div>
        </n-space>
      </div>
    </n-spin>
    <n-divider />
    <UsageGuide
      :title="usageGuideConfig.title"
      :steps="usageGuideConfig.steps"
      :tips="usageGuideConfig.tips"
      :example="usageGuideConfig.example"
    />
  </PageCard>
</template>

<script setup lang="ts">
import {ref, onMounted} from 'vue';
import {getAddress, getCurrentAddress} from "@/api/ip/IpApi.ts";
import PageCard from "@/components/PageCard.vue";
import UsageGuide from "@/components/UsageGuide.vue";

const ipValue = ref('');
const result = ref('');
const loading = ref(false);
const error = ref('');

// UsageGuide configuration
const usageGuideConfig = {
  title: '使用说明',
  steps: [
    '页面加载时会自动获取您当前的IP地址和位置信息',
    '您也可以输入任意IP地址进行查询',
    '点击查询按钮或按回车键执行查询'
  ],
  tips: [
    '支持IPv4和IPv6地址查询',
    '查询结果包含IP所在的地理位置信息',
    '自动检测功能依赖于您的网络环境'
  ],
  example: '输入示例：8.8.8.8、192.168.1.1、2001:4860:4860::8888'
};

const handleSearch = () => {
  if (!ipValue.value) return;
  loading.value = true;
  error.value = '';
  getAddress(ipValue.value)
      .then((value: any) => {
        result.value = value.data.data.address;
      })
      .catch((err: any) => {
        error.value = `查询失败: ${err.message || '未知错误'}`;
        result.value = '';
      })
      .finally(() => {
        loading.value = false;
      });
};

onMounted(() => {
  loading.value = true;
  error.value = '';
  getCurrentAddress()
      .then((value: any) => {
        ipValue.value = value.data.ip;
        result.value = value.data.address;
      })
      .catch((err: any) => {
        error.value = `获取当前地址失败: ${err.message || '未知错误'}`;
      })
      .finally(() => {
        loading.value = false;
      });
});
</script>

<style lang="less" scoped>
</style>
